//
//  OrdinaryTeacherAddVC.m
//  优学荟管理系统
//
//  Created by 星道 on 2017/10/6.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "OrdinaryTeacherAddVC.h"
#import "AFNetworking.h"
#import <SDWebImage/UIButton+WebCache.h>

@interface OrdinaryTeacherAddVC ()<UITextFieldDelegate, UITextViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>
{
    IBOutlet UILabel *_ImgLabel;
    IBOutlet UIImageView *_Img;
    IBOutlet UITextField *_Name;
    IBOutlet UITextField *_Phone;
    IBOutlet UITextField *_Pwd;
    IBOutlet UITextField *_Email;
    IBOutlet UITextView *_Content;
    IBOutlet UILabel *_ContentLabel;
    IBOutlet UIButton *_Sure;
    IBOutletCollection(UIButton) NSArray *Imgs;
    __weak IBOutlet UITextField *_TeacherId;
    
    /** 选择图片的回调 */
    void (^_SelectImg)(UIImage *img);
}
@end

@implementation OrdinaryTeacherAddVC

#pragma mark - cycle life
- (void)viewDidLoad {

    [super viewDidLoad];

    self.title = self.ID ? @"修改老师账号":@"添加老师账号";
    _TeacherId.userInteractionEnabled = self.ID ? NO:YES;

    // 头像添加手势
    [_Img addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ClickHeaderImg)]];
    [_ImgLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ClickHeaderImg)]];

    self.ID ? [self RefreshDataComplete:^(NSDictionary *Dict) {
        // 界面赋值
        [self CreatUI:Dict];
    }]:nil;
}

#pragma mark - 网络
/** 如果是修改得先发起网络请求 */
- (void)RefreshDataComplete:(void (^)(NSDictionary *Dict))Complete {

    [SVProgressHUD showWithStatus:@"获取老师信息中"];
    NSDictionary *Params = @{
                             @"action":@"teachserInfo",
                             @"uid":self.ID
                             };
    [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:Params Success:^(id Obj) {
        if ([Obj[@"code"] isEqualToNumber:@1000]) {
            [SVProgressHUD dismiss];
            dispatch_async(dispatch_get_main_queue(), ^{
                Complete ? Complete (Obj[@"t"]):nil;
            });
        } else {
            [SVProgressHUD showErrorWithStatus:Obj[@"msg"]];
        }
    } Fail:^(NSError *Error) {
        [SVProgressHUD showErrorWithStatus:NetErr];
    }];
}


#pragma mark - action
/** 赋值 */
- (void)CreatUI:(NSDictionary *)Dict {

    [_Img sd_setImageWithURL:[NSURL URLWithString:Dict[@"imageUrl"]]];
    if ([NSString isBlankString:Dict[@"realName"]]) {
        _Name.text = @"";
    } else {
        _Name.text = Dict[@"realName"];
    }
    if ([NSString isBlankString:Dict[@"phone"]]) {
        _Phone.text = @"";
    } else {
        _Phone.text = Dict[@"phone"];
    }
   
    if ([NSString isBlankString:Dict[@"username"]]) {
        _TeacherId.text = @"";
    } else {
        _TeacherId.text = [NSString stringWithFormat:@"%@",Dict[@"username"]];
    }
    
    BOOL isUp =  [NSString isBlankString:[Dict valueForKey:@"email"]];
    
    
    if (isUp) {
        
    }else{
        _Email.text = [NSString stringWithFormat:@"%@",Dict[@"email"]];
        
    }
    
    _Content.text = Dict[@"desc"];
    _ContentLabel.hidden = _ContentLabel.text.length;
    [Dict[@"paths"] enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *Button = Imgs[idx];
        [Button sd_setImageWithURL:[NSURL URLWithString:obj] forState:(UIControlStateSelected) completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            Button.selected = YES;
        }];
    }];
}


/** 添加图片 */
- (IBAction)ClickImgBtn:(UIButton *)sender {

    sender.selected ? [self DeleteImg:sender]:[self AlertController:^(UIImage *img) {
        sender.selected = !sender.selected;
        [sender setImage:img forState:(UIControlStateSelected)];
    }];
}

/** 头像 */
- (void)ClickHeaderImg {

    [self AlertController:^(UIImage *img) {
        _Img.image = img;
    }];
}

/** 保存 */
- (IBAction)Save:(UIButton *)sender {

    // 判断文本长度
    if (_Name.text.length <= 0 ||
        _Phone.text.length <= 0 ||
        _Pwd.text.length <= 0 ||
        _Email.text.length <= 0 ||
        _TeacherId.text.length <= 0) {

        [SVProgressHUD showInfoWithStatus:@"请完善必填项"];
        return;
    }

    if (![LLTools isEmailAddressRight:_Email.text]) {
        [SVProgressHUD showInfoWithStatus:@"请正确的邮箱地址!"];
        return;
    }

    if (_Pwd.text.length < 6) {
        [SVProgressHUD showInfoWithStatus:@"密码长度必须大于等于6位"];
        return;
    }

    // 得到老师风采
    NSMutableArray *ImgArr = [NSMutableArray array];
    [Imgs enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.selected) {
            [ImgArr addObject:obj.imageView.image];
        }
    }];

    [SVProgressHUD showWithStatus:@"请稍候"];
    NSDictionary *Params = @{
                             @"action":@"registerTeacher",
                             @"oid"   :[AccountTool shareAccountTool].currentAccount.oid,
                             @"phone" :_Phone.text,
                             @"password":_Pwd.text,
                             @"petName":_Name.text,
                             @"desc":_Content.text,
                             @"email":_Email.text,
                             @"username":_TeacherId.text
                             };
    // 如果是修改信息就用得上下面的了
    NSMutableDictionary *TempParams = [NSMutableDictionary dictionary];
    if (self.ID) {
        [TempParams setValuesForKeysWithDictionary:Params];
        [TempParams setValue:self.ID forKey:@"uid"];
        [TempParams setValue:@1 forKey:@"type"];
    }
    [self UpdataImgsWithURL:LLBaseURL(@"lesson.do") img:_Img.image imgs:ImgArr parameter:self.ID? TempParams:Params Progress:^(NSProgress * _Nonnull uploadProgress) {
        if (uploadProgress.totalUnitCount == uploadProgress.completedUnitCount)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showWithStatus:@"请稍候"];
            });
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showWithStatus:[NSString stringWithFormat:@"总大小：%.2fM,当前大小:%.2fM",uploadProgress.totalUnitCount/1024.0/1024.0,uploadProgress.completedUnitCount/1024.0/1024.0]];
            });
        }
    } success:^(id obj) {
        [SVProgressHUD dismiss];
        NSDictionary *Dict = [NSJSONSerialization JSONObjectWithData:obj options:(NSJSONReadingMutableLeaves) error:nil];
        if ([Dict[@"code"] isEqualToNumber:@1000]) {
            
            if (self.ID) {
                if (self.popBlock) {
                    self.popBlock();
                }
                [self.navigationController popViewControllerAnimated:YES];
            }else{

                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (self.popBlock) {
                            self.popBlock();
                        }
                        [self.navigationController popViewControllerAnimated:YES];
                    });

            }
            
            
            
        } else {
            [SVProgressHUD showErrorWithStatus:Dict[@"msg"]];
        }
    } fail:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:NetErr];
    }];
}

#pragma mark - textField、textView代理
- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    if (textField == _Email) {

        [self.view endEditing:YES];
    } else {

        UITextField *tempTextField = (UITextField *)[self.view viewWithTag:textField.tag + 1];
        [tempTextField becomeFirstResponder];
    }
    return YES;
}
/** 监控提示的消失与显示 */
- (void)textViewDidChange:(UITextView *)textView
{
    _ContentLabel.hidden = textView.text.length;
}

#pragma mark - Upload net
// 多张图片、多种类型以及其他信息上传
- (void)UpdataImgsWithURL:(NSString *)url img:(UIImage *)img imgs:(NSArray <UIImage *>*)imgs parameter:(NSDictionary *)paraDic Progress:(void (^)(NSProgress * _Nonnull uploadProgress))Progress success:(void (^)(id obj))success fail:(void (^)(NSError *error))fail
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 30;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/html", nil];
    [manager.requestSerializer setValue:[AccountTool shareAccountTool].currentAccount.authCode forHTTPHeaderField:@"auth"];

    [manager POST:url parameters:paraDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

        [imgs enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSData *imageData = UIImageJPEGRepresentation(obj, 0.4);
            [formData appendPartWithFileData:imageData name:@"file" fileName:[NSString stringWithFormat:@"%ld.jpg",idx] mimeType:@"image/jpeg"];
        }];

        if (img) {
            NSData *imageData = UIImageJPEGRepresentation(img, 0.4);
            [formData appendPartWithFileData:imageData name:@"img" fileName:[NSString stringWithFormat:@"img10086.jpg"] mimeType:@"image/jpeg"];
        }

    } progress:Progress success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        [MBProgressHUD hideHUD];
        success (responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        [MBProgressHUD hideHUD];
        fail (error);

    }];
}

- (void)viewDidLayoutSubviews {

    [super viewDidLayoutSubviews];
    _Img.layer.masksToBounds = YES;
    _Img.layer.cornerRadius = _Img.frame.size.width/2;
}


#pragma mark - 上传图片
/** AlertController 增加图片*/
- (void)AlertController:(void (^)(UIImage *img))Complete
{
    _SelectImg = Complete;
    UIAlertController *AlertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请选择图片来源" preferredStyle:(UIAlertControllerStyleActionSheet)];
    [AlertController addAction:[UIAlertAction actionWithTitle:@"相机" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self ConfigImagePickController:YES];
    }]];
    [AlertController addAction:[UIAlertAction actionWithTitle:@"从相册中选择" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self ConfigImagePickController:NO];
    }]];
    [AlertController addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:AlertController animated:YES completion:nil];
}

/** 删除按钮上的图片 */
- (void)DeleteImg:(UIButton *)Button
{
    UIAlertController *AlertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"是否删除已上传的图片?" preferredStyle:(UIAlertControllerStyleActionSheet)];
    [AlertController addAction:[UIAlertAction actionWithTitle:@"删除" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {
        Button.selected = !Button.selected;
    }]];
    [AlertController addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:AlertController animated:YES completion:nil];
}


/** 初始相机与相册 ,根据isCamera调用相机或相册*/
- (void)ConfigImagePickController:(BOOL)isCamera
{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType = isCamera ? UIImagePickerControllerSourceTypeCamera:UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:imagePicker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *img = [info objectForKey:UIImagePickerControllerOriginalImage];
    [picker dismissViewControllerAnimated:YES completion:^{
        if (_SelectImg)
        {
            _SelectImg (img);
        }
    }];
}

-(void)viewWillDisappear:(BOOL)animated {
    [SVProgressHUD dismiss];
}

@end
